package databases

import (
	"errors"
	"strconv"
	"time"

	"github.com/go-xorm/xorm"
	"gitlab.gaodun.com/golib/gderror"
	"permission/config"
	"permission/vigo_loger"
)

type UsersFactory struct {
	Table         Tpo_Sys_Users
	engine        *xorm.Engine
	RowsSlicePtr  []Tpo_Sys_Users
	DepartUserPtr []UserDepartment
}

// 返回 user factory
func NewUserFactory() *UsersFactory {
	userFac := UsersFactory{}
	userFac.engine, _ = config.InitEng()
	return &userFac
}

func (udf *UsersFactory) EditPwd(userId int64, password string) error {
	if password == "" {
		return errors.New("new password is null")
	}
	_, err := udf.engine.Where("UserID = ?", userId).Update(&Tpo_Sys_Users{Password: password, CallContent: CallContent{UpdatePwd_Date: time.Now()}})
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

func (udf *UsersFactory) EditUserDaili(userId int64) error {
	_, err := udf.engine.Where("UserID = ?", userId).Update(&(udf.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err

}

// 根据手机号获取用户
func (udf *UsersFactory) GetUserInfoByPhone(phone string) (bool, error) {
	if phone == "" {
		return false, errors.New("phone is null")
	}
	res, err := udf.engine.Where(" Mobile = ? and IsDelete != ? and Isleave != ?", phone, 1, 1).Get(&(udf.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return res, err
}

func (udf *UsersFactory) GetUserInfoByPartialPhone(phone string) (bool, error) {
	if phone == "" {
		return false, errors.New("phone is null")
	}
	res, err := udf.engine.Where(" PartialPhone = ? and IsDelete != ? and Isleave != ?", phone, 1, 1).Get(&(udf.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return res, err
}

func (udf *UsersFactory) GetUserInfoByPhones(phones ...string) error {
	if len(phones) == 0 {
		return errors.New("phone is null")
	}
	return udf.engine.Where("IsDelete != ? and Isleave != ?", 1, 1).In("Mobile", phones).Find(&udf.RowsSlicePtr)
}

// 根据邮箱获取用户
func (udf *UsersFactory) GetUserInfoByEmail(email string) (bool, error) {
	if email == "" {
		return false, errors.New("Email is null")
	}
	res, err := udf.engine.Where(" Email = ? and IsDelete != ? and Isleave != ? ", email, 1, 1).Get(&(udf.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return res, err
}

// 根据 id 获取用户
func (udf *UsersFactory) GetUserInfoByUserId(userId int64) (bool, error) {
	if userId == 0 {
		return false, errors.New("userId is null")
	}
	res, err := udf.engine.Where(" UserID = ? and Isleave != ? and IsDelete != ? ", userId, 1, 1).Get(&(udf.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return res, err
}

func (udf *UsersFactory) FindUserInfoByPartialPhone(phones ...string) error {
	if len(phones) == 0 {
		return errors.New("phone is null")
	}

	err := udf.engine.In("PartialPhone", phones).Find(&(udf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

func (udf *UsersFactory) FindUserInfoByTrAgentNo(agentNos ...string) error {
	if len(agentNos) == 0 {
		return errors.New("TrAgentNo is null")
	}

	err := udf.engine.In("TrAgentNo", agentNos).Find(&(udf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

// 根据 ids 获取用户
func (udf *UsersFactory) FindUserInfoIds(userIds ...int64) error {
	if len(userIds) == 0 {
		return errors.New("userId is null")
	}
	//err := udf.engine.In("UserID", userIds).Where(" Isleave != ? and IsDelete != ? ", 1, 1).Find(&(udf.RowsSlicePtr))
	err := udf.engine.In("UserID", userIds).Find(&(udf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

// FindUserInfoErp 根据ERPID获取
func (udf *UsersFactory) FindUserInfoErp(erpIds ...string) error {
	if len(erpIds) == 0 {
		return errors.New("erpId is null")
	}
	err := udf.engine.In("ErpUserId", erpIds).Find(&(udf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

// 获取所有用户
func (udf *UsersFactory) FindAll() error {

	//err := udf.engine.Where(" Isleave != ? and IsDelete != ? ", 1, 1).Find(&(udf.RowsSlicePtr))
	err := udf.engine.Find(&(udf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	return err
}

func toInt(s string) int {
	i, _ := strconv.ParseInt(s, 10, 64)
	return int(i)
}

// 获取所有用户部门
func (udf *UsersFactory) FindUserDepartAll(f bool) {
	// udf.engine.Table("Tpo_Sys_Users").Join("INNER", "Tpo_Sys_Department_User", "Tpo_Sys_Department_User.UserId=Tpo_Sys_Users.UserID").Find(&(udf.DepartUserPtr))
	udf.DepartUserPtr = []UserDepartment{}
	var uids []int64
	sql := " SELECT * FROM `Tpo_Sys_Users` INNER JOIN `Tpo_Sys_Department_User` ON Tpo_Sys_Department_User.UserId=Tpo_Sys_Users.UserID where Tpo_Sys_Users.Isleave<>1 and Tpo_Sys_Users.IsDelete<>1"
	if f {
		sql = " SELECT * FROM `Tpo_Sys_Users` INNER JOIN `Tpo_Sys_Department_User` ON Tpo_Sys_Department_User.UserId=Tpo_Sys_Users.UserID "
	}
	m, _ := udf.engine.Query(sql)
	for _, value := range m {
		userDepart := UserDepartment{}

		userId, _ := strconv.ParseInt(string(value["userid"]), 10, 64)
		userDepart.UserID = userId
		sex, _ := strconv.ParseInt(string(value["sex"]), 10, 32)
		userDepart.Sex = int32(sex)
		IsPublic, _ := strconv.ParseInt(string(value["ispublic"]), 10, 32)
		userDepart.IsPublic = int32(IsPublic)
		DeparentId, _ := strconv.ParseInt(string(value["DeparentId"]), 10, 64)
		userDepart.DeparentId = DeparentId
		userDepart.Ename = string(value["ename"])
		userDepart.WorkNo = string(value["workno"])
		userDepart.UserName = string(value["username"])
		userDepart.Mobile = string(value["mobile"])
		userDepart.Email = string(value["email"])
		userDepart.TrueName = string(value["truename"])
		userDepart.Avatar = string(value["avatar"])
		userDepart.Birthday = string(value["birthday"])
		userDepart.Qq = string(value["qq"])
		userDepart.CreateTime = string(value["createtime"])
		userDepart.CourseTypes = string(value["coursetypes"])
		userDepart.AgentType = toInt(string(value["agenttype"]))
		userDepart.AgentSubType = toInt(string(value["agentsubtype"]))
		userDepart.IsAgent = toInt(string(value["isagent"]))

		uids = append(uids, userDepart.UserID)
		udf.DepartUserPtr = append(udf.DepartUserPtr, userDepart)
	}

	urf := NewUserRolesFactory()
	err := urf.FindInfoByUserIds(uids...)
	if err == nil {
		for i, du := range udf.DepartUserPtr {
			for _, ur := range urf.RowsSlicePtr {
				if du.UserID == ur.UserId {
					du.UserRole = append(du.UserRole, ur)
				}
			}
			udf.DepartUserPtr[i] = du
		}
	}
}

func (udf *UsersFactory) FindAllLeaderUser() error {
	err := udf.engine.Join("INNER", "Tpo_Sys_Departments", "Tpo_Sys_Users.UserID in (Tpo_Sys_Departments.leader_id)").Find(&(udf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

func (udf *UsersFactory) ExistErpUerId(erpUserId string) (bool, error) {
	return udf.engine.Where("ErpUserId = ?", erpUserId).Get(&(udf.Table))
}

func (udf *UsersFactory) Add() (int64, error) {
	row, err := udf.engine.InsertOne(&(udf.Table))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return row, err
}

// 根据 条件 获取用户
func (udf *UsersFactory) GetUserByCondition(userId string, mainroleInt string, TrueNameStr string, deparentIdInt string, offsetInt string, limitInt string) {
	udf.DepartUserPtr = []UserDepartment{}
	sql := " SELECT `Tpo_Sys_Users`.*,`Tpo_Sys_Department_User`.DeparentId as deparentId,`Tpo_Sys_Departments`.Name as departmentName FROM `Tpo_Sys_Users` LEFT OUTER JOIN `Tpo_Sys_Department_User` ON `Tpo_Sys_Users`.userid = `Tpo_Sys_Department_User`.UserId LEFT OUTER JOIN `Tpo_Sys_Departments` ON `Tpo_Sys_Department_User`.DeparentId = `Tpo_Sys_Departments`.DeparentId where Tpo_Sys_Users.isdelete<>1 and isleave<>1"
	if userId != "" {
		sql += " and `Tpo_Sys_Users`.userid in ("+userId+")"
	}
	if mainroleInt != "" {
		sql += " and `Tpo_Sys_Users`.mainrole = "+mainroleInt
	}else{
		sql += " and `Tpo_Sys_Users`.mainrole in (1006001, 1006002)"
	}
	if TrueNameStr != "" {
		sql += " and `Tpo_Sys_Users`.truename like '%"+TrueNameStr+"%'"
	}
	if deparentIdInt != "" {
		sql += " and `Tpo_Sys_Departments`.DeparentId = "+deparentIdInt
	}
	if limitInt != ""{
		sql += " limit "+offsetInt+", "+limitInt
	}

	res, _ := udf.engine.Query(sql)
	for _, value := range res{
		userDepart := UserDepartment{}

		userId, _ := strconv.ParseInt(string(value["userid"]), 10, 64)
		userDepart.UserID = userId
		sex, _ := strconv.ParseInt(string(value["sex"]), 10, 32)
		userDepart.Sex = int32(sex)
		IsPublic, _ := strconv.ParseInt(string(value["ispublic"]), 10, 32)
		userDepart.IsPublic = int32(IsPublic)
		DeparentId, _ := strconv.ParseInt(string(value["deparentId"]), 10, 64)
		userDepart.DeparentId = DeparentId
		userDepart.DeparentName = string(value["departmentName"])
		userDepart.Ename = string(value["ename"])
		userDepart.WorkNo = string(value["workno"])
		userDepart.UserName = string(value["username"])
		userDepart.Mobile = string(value["mobile"])
		userDepart.Email = string(value["email"])
		userDepart.TrueName = string(value["truename"])
		userDepart.Avatar = string(value["avatar"])
		userDepart.Birthday = string(value["birthday"])
		userDepart.Qq = string(value["qq"])
		userDepart.CreateTime = string(value["createtime"])
		userDepart.CourseTypes = string(value["coursetypes"])
		userDepart.AgentType = toInt(string(value["agenttype"]))
		userDepart.AgentSubType = toInt(string(value["agentsubtype"]))
		userDepart.IsAgent = toInt(string(value["isagent"]))
		udf.DepartUserPtr = append(udf.DepartUserPtr, userDepart)
	}
	
}
